import { NavigateFunction } from "react-router-dom";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { userLogin } from "../api/user";
import { IUserParams, UserInfoType } from "../type/course";
interface UserStateType {
  userInfo: UserInfoType | null;
  loading: boolean;
  userLoginAsync: (
    userObj: IUserParams,
    navigate: NavigateFunction,
    target: string
  ) => void;
  logout: () => void;
  update: (info: UserInfoType) => void;
}
export const useUserStore = create<UserStateType>()(
  persist(
    (set) => ({
      userInfo: null,
      loading: false,
      userLoginAsync: async (userObj, navigate, target) => {
        set({ loading: true });
        setTimeout(async () => {
          try {
            let res = await userLogin(userObj);
            console.log("成功", res);
            set({ userInfo: res.data });
            target ? navigate(target) : navigate(-1);
          } catch (err) {
            console.log("失败", err);
          }
          set({ loading: false });
        }, 1000);
      },
      //退出登录
      logout() {
        set({ userInfo: null });
      },
      update(info) {
        set({ userInfo: info });
      },
    }),
    { name: "zustand-mobile-user-info" }
  )
);
